﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CRMSimple.LogService.Configuration.FileConfigurationExtension.Json;
using BitAuto.EP.Plat.Util;
using BitAuto.EP.CRMLogSystem.Utils;
using System.Threading;
using BitAuto.EP.FuncPMonitor.Aops;

namespace CRMSimple.LogServices
{
   public static class ConfigurationManagerExtensions
    {

       public static string GetAppSettingsPath(this ConfigurationManager manger,string appKey)
       {
           return Path.Combine(manger.AppSettingsPath, string.Format("{0}_{1}", appKey, manger.AppSettingsName));
       }
       [FuncPMonitor()]
       public static JsonConfigurationRoot LoadJsonConfig(this ConfigurationManager manger, JsonConfigurationRoot jsonConfig,int count=0)
       {
           try
           {
               jsonConfig.Load();
               if (!jsonConfig.Properties.Any())
               { 
                    //写入预设置的模版
                   jsonConfig.InsertJsonConfig(manger.JsonConfigTemplate.Properties);
                   jsonConfig.Write();
               }
           }
           catch (Exception ex)
           {
               //某一个配置文件出了问题
               string content = string.Format("配置文件加载异常");
               LogExceptionRoot.ContextLog.Info(content, ex);
               ErrorAlertMailHelper.SendAlertMail("日志服务入库异常", content + "异常：" + ex.Message + ex.StackTrace);
               Thread.Sleep(5);
               if(count<2)
                   LoadJsonConfig(manger, jsonConfig, count++);
           }
           return jsonConfig;
       }
       [FuncPMonitor()]
       public static void WriteJsonConfig(this ConfigurationManager manger, JsonConfigurationRoot jsonConfig, int count = 0)
       {
           try
           {
               jsonConfig.Write();
           }
           catch (Exception ex)
           {
               string content = string.Format("配置文件写入异常");
               //DataLogHelper.E(content, ex);
               LogExceptionRoot.ContextLog.Info(content, ex);
               ErrorAlertMailHelper.SendAlertMail("日志服务入库异常", content + "异常：" + ex.Message + ex.StackTrace);
               Thread.Sleep(5);
               if (count < 2)
                   WriteJsonConfig(manger, jsonConfig, count++);
           }
       }
    }
}
